package com.xdxc.utils;

import com.xdxc.entity.SysUser;
import com.xdxc.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Map;

@Component
public class SecurityUtils {

    private static AuthenticationManager authenticationManager;


    @Autowired
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        SecurityUtils.authenticationManager = authenticationManager;
    }

    /**
     * 获取当前登录用户
     */
    public static UserDetails getCurrentUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            throw new CustomException(401, "用户未登录");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            return (UserDetails) principal; // 安全地转换为 UserDetails
        } else if (principal instanceof String) {
            UserDetails admin = User.builder()
                    .username((String) principal) // 设置用户名
                    .password("") // 设置一个空密码（不能为 null）
                    .authorities(authentication.getAuthorities()) // 设置空权限列表（不能为 null）
                    .build();
            return admin;
        } else {
            throw new CustomException(500, "未知的 Principal 类型：" + principal.getClass().getName());
        }
    }

    /**
     * 获取当前用户名
     */
    public static String getCurrentUsername() {
        return getCurrentUser().getUsername();
    }

    /**
     * 获取当前用户ID
     */
    public static Long getCurrentUserId() {
        Authentication authentication = getAuthentication();
        if (authentication != null && authentication.getDetails() instanceof Map) {
            Map<String, Object> details = (Map<String, Object>) authentication.getDetails();
            // 从 Map 中获取 userId
            Object userIdObj = details.get("userId");
            if (userIdObj != null) {
                Long userId = (Long) userIdObj; // 假设 userId 是字符串类型
                System.out.println("User ID: " + userId);
                return userId;
            } else {
                System.out.println("User ID not found in details.");
            }
        } else {
            System.out.println("Authentication or details is null.");
        }
        throw new CustomException(500,"用户信息解析失败");
    }

    private static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 用户登录
     */

}